//
//  RegisterFinishViewController.m
//  HuLaQuan
//
//  Created by hok on 1/13/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "RegisterFinishViewController.h"

#import "LoginRelatedHeader.h"

//Views
#import "YuLoginInputInfoField.h"

#import "YuVerifyButton.h"

// SMS logic Model

#import "SMSVerifyEngine.h"

//Utility
#import "YuLoginRegisterUtilities.h"

//Jump To Next Controller
#import "RegisterFirstInputPasswordController.h"


@interface RegisterFinishViewController()<UIGestureRecognizerDelegate>
{
    NSInteger count;
}
@property(strong,nonatomic)NSTimer *timerCount;

//确认按钮
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;

//获取验证码按钮
@property (weak, nonatomic) IBOutlet YuVerifyButton *verifyCodeButton;
//用户名文本框
@property (weak, nonatomic) IBOutlet YuLoginInputInfoField *mobileField;
//验证码文本框
@property (weak, nonatomic) IBOutlet YuLoginInputInfoField *verifyCodeField;

@property (nonatomic,strong) SMSVerifyEngine *smsVerifyEngine;
@end


@implementation RegisterFinishViewController

- (SMSVerifyEngine *)smsVerifyEngine
{
    if (!_smsVerifyEngine) {
        _smsVerifyEngine = [[SMSVerifyEngine alloc] init];
    }
    return _smsVerifyEngine;
}
#pragma mark - Setup
- (void)setupUI
{
    self.title = @"快速注册";
    [self setupNavBackButton];
    
    [self setupTextField];
    
    // 加手势处理键盘
    [self setupTapGesture];
    
    
    if (self.mobileField.text.length == 0 || self.verifyCodeField.text.length == 0) {
        self.confirmButton.enabled = NO;
    }
}

// 加手势处理键盘
- (void)setupTapGesture
{
    UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handelGenericTapView:)];
    tapRec.delegate = self;
    [self.view addGestureRecognizer:tapRec];
}
- (void)handelGenericTapView:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        // handling code
        // [self.view endEditing:YES];
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
    }
}

- (void)setupTextField
{
    //    self.nameField.imageName = @"name.png";
    //    self.secretField.imageName = @"password.png";
    [self.mobileField setColorfulPlaceholder:kNumberFiledPlaceholder];
    [self.verifyCodeField setColorfulPlaceholder:kverifyFiledPlaceholder];
}

#pragma mark - Button Events
//确认按钮事件(检验验证码)
- (IBAction)tapConfirmButton:(id)sender {
    
    /**
     * Final
     *
     *  @param self.verifyCodeField.text.length 验证码为6位数字
     *
     *  @return <#return value description#>
     */
    if (self.verifyCodeField.text && self.verifyCodeField.text.length == 6) {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.smsVerifyEngine verifySMSWithcode:self.verifyCodeField.text];
    }else{
        [self.view makeToast:kVerifyCodeInvalid];
    }
    
}

//获取验证码点击事件
- (IBAction)tapVerifyCodeButton:(id)sender {
    if (self.mobileField.text && [YuLoginRegisterUtilities isMobileNumber:self.mobileField.text] ) {
        [self beginTimerForVerify];
        
        self.smsVerifyEngine.smsType = SMSRegister;
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.smsVerifyEngine getSMSWithMobile:self.mobileField.text];
    }else{
        [self.view makeToast:@"您输入的手机号码不正确，请检查后重新输入"];
    }
    
}
#pragma mark - Call Back
- (void)getSMSVeriCodeFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
- (void)verifySMSVeriCodeFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        if (messageDic[@"result"] && [messageDic[@"result"] isKindOfClass:[NSDictionary class]]) {
            self.registerInfoDic = messageDic[@"result"];
            [self performSegueWithIdentifier:@"ShowFirstInputPWFromRegisterFinish" sender:self];
        }
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
#pragma mark - Controller Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSMSVeriCodeFinish:) name:@"GetSMSVeriCodeFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(verifySMSVeriCodeFinish:) name:@"VerifySMSVeriCodeFinish" object:nil];
    
    [self.mobileField becomeFirstResponder];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetSMSVeriCodeFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VerifySMSVeriCodeFinish" object:nil];
    [self.timerCount invalidate];
    
    [super viewWillDisappear:YES];
    
}
#pragma mark - Timer
- (void)beginTimerForVerify
{
    count = kverifyTimerSetting;
    self.timerCount = [NSTimer scheduledTimerWithTimeInterval:1
                                                       target:self
                                                     selector:@selector(timerForVeirify:)
                                                     userInfo:nil
                                                      repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timerCount
                                 forMode:NSRunLoopCommonModes];
    self.verifyCodeButton.enabled = NO;
}

- (void)timerForVeirify:(NSTimer *)timer
{
    [self.verifyCodeButton setTitle:[NSString stringWithFormat:@"%ld秒后点击",count] forState:UIControlStateNormal];
    
    if (count == 0) {
        [self resetVerifyButton:self.verifyCodeButton];
        [timer invalidate];
    }
    count--;
}
- (void)resetVerifyButton:(UIButton *)button
{
    button.enabled = YES;
    [button setTitle:@"获取验证码" forState:UIControlStateNormal];
}


#pragma mark - Textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
    [textF setColorfulPlaceholder:@""];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text.length == 0 ) {
        YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
        [textF setColorfulPlaceholder:([textField isEqual:self.mobileField] ? kNumberFiledPlaceholder : kverifyFiledPlaceholder)];
        
    }
    if (self.mobileField.text.length == 0 || self.verifyCodeField.text.length == 0) {
        self.confirmButton.enabled = NO;
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (self.mobileField.text.length > 0 && self.verifyCodeField.text.length > 0) {
        self.confirmButton.enabled = YES;
    }
    return YES;
    
    // return [self validateNumber:string];
}



#pragma mark - Navigation


- (void)goBackAction
{
    
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"是否放弃注册新用户" andBlock:^(UIAlertAction *action ) {
        if ([action.title isEqualToString:@"好的"]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }
        
    }  type:@"confirmAndCancel"];
    [self presentViewController:x animated:YES completion:nil];
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([[segue identifier] isEqualToString:@"ShowFirstInputPWFromRegisterFinish"]) {
        RegisterFirstInputPasswordController *controller = (RegisterFirstInputPasswordController*) [segue destinationViewController];
        controller.type = UserPassword;
        controller.passwordAndInfos[@"userName"] = self.mobileField.text;
        controller.passwordAndInfos[@"tokenValue"] = self.registerInfoDic[@"tokenValue"];
        controller.titleOfNav = kSetUserPasswordTitle;
        controller.titleOfPassword = kSetUserPasswordHint;
    }
}

@end
